package icu.lookyousmileface.netty.simple.mylmpl;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

/**
 * @author shenj
 * @title: ServerHandler
 * @projectName NettyPro
 * @date 2020/12/4 8:18
 */
public class ServerHandler  extends ChannelInboundHandlerAdapter  {
    /**
     * @author shenj
     * @title: channelRead
     * @date 2020/12/4  8:24
     * read
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ctx.channel().eventLoop().execute(()->{
            try {
                Thread.sleep(5*1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("来自服务器的第二条信息", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        ctx.channel().eventLoop().execute(()->{
            try {
                Thread.sleep(5*1000);
                ctx.writeAndFlush(Unpooled.copiedBuffer("来自服务器的第三条信息", CharsetUtil.UTF_8));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        ctx.channel().eventLoop().schedule(()-> {
                try {
                    Thread.sleep(5*1000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("来自服务器的第四条信息", CharsetUtil.UTF_8));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            },5,TimeUnit.SECONDS);
        System.out.println("This is debug");
    }
    /**
     * @author shenj
     * @title: channelReadComplete
     * @date 2020/12/4  8:24
     * channelReadComplete send Info
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("来自服务器的第一条信息",CharsetUtil.UTF_8));
    }
    /**
     * @author shenj
     * @title: exceptionCaught
     * @date 2020/12/4  8:25
     * try Bug
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
